/*Mid窗体页面类*/
jQuery.extend({
    yqFormMdi_fun: function (action, param) {
        switch (action) {
            case "form_setup":  //页面设置
                return {
                    text: "页面配置",
                    iconCls: "yqwin-btn-icon-sub fa fa-picture-o",
                    onClick: function () {
                        var $pp = $(this);

                        var _pops = {
                            prevent_e: {         //调用组件信息
                                id: "",
                                options: {},  //调用组件jquery对象
                                clientX: 0,
                                clientY: 0
                            },
                            mdiinfo: {            //mdi窗体信息
                                clientX: 0,
                                clientY: 0
                            },
                            horizontalAlign: "center",
                            verticalAlign: "center",
                            showTitle: true,
                            title: '<span class="yqwin-btn-icon fa fa-picture-o"></span>页面配置',
                            width: 450,
                            height: 350,
                            closeBtnText: '关闭',
                            onOpen: function ($body) {
                                //console.log("$body", $body);
                                var div = '<div style="margin:10px 0 20px 15px">';
                                div += '  <select name="theme" style="width:100%"></select>';
                                div += '</div>';
                                var $div = $(div);
                                var $theme = $div.find('[name="theme"]');
                                $theme.combobox({
                                    label: "theme",
                                    labelWidth: 60,
                                    groupField: 'group',
                                    width: 235,
                                    valueField: 'value',
                                    textField: 'text',

                                    data: [
                                        { value: 'default', text: 'Default', group: 'Base' },
                                        { value: 'gray', text: 'Gray', group: 'Base' },
                                        { value: 'metro', text: 'Metro', group: 'Base' },
                                        { value: 'material', text: 'Material', group: 'Base' },
                                        { value: 'material-teal', text: 'Material Teal', group: 'Base' },
                                        { value: 'material-blue', text: 'Material Blue', group: 'Base' },
                                        { value: 'bootstrap', text: 'Bootstrap', group: 'Base' },
                                        { value: 'black', text: 'Black', group: 'Base' },
                                        { value: 'metro-blue', text: 'Metro Blue', group: 'Metro' },
                                        { value: 'metro-gray', text: 'Metro Gray', group: 'Metro' },
                                        { value: 'metro-green', text: 'Metro Green', group: 'Metro' },
                                        { value: 'metro-orange', text: 'Metro Orange', group: 'Metro' },
                                        { value: 'metro-red', text: 'Metro Red', group: 'Metro' },
                                        { value: 'ui-cupertino', text: 'Cupertino', group: 'UI' },
                                        { value: 'ui-dark-hive', text: 'Dark Hive', group: 'UI' },
                                        { value: 'ui-pepper-grinder', text: 'Pepper Grinder', group: 'UI' },
                                        { value: 'ui-sunny', text: 'Sunny', group: 'UI' }
                                    ],
                                    icons: [{
                                        iconCls: 'yqwin-combo-btn-icon fa fa-refresh',
                                        handler: function (e) {
                                            location.reload();
                                        }
                                    }],
                                    onLoadSuccess: function () {
                                        var l = localStorage.getItem('easyui_theme');
                                        if (l === null) {
                                            l = "default";
                                        }
                                        $(this).combobox('setValue', l);
                                        var $btn = $(this).combobox('getIcon', 0);
                                        $btn.attr("title", "刷新主页面");
                                    },
                                    onChange: function (newValue, oldValue) {
                                        localStorage.setItem('easyui_theme', newValue);
                                        var link = $('#easyui_themes');
                                        var href = '/yqwin/easyui/themes/' + newValue + '/easyui.css';
                                        if (href != link.attr('href')) {
                                            link.attr('href', href);
                                        }
                                        link = $('#yqwin_themes');
                                        href = '/yqwin/css/' + newValue + '.css';
                                        if (href != link.attr('href')) {
                                            link.attr('href', href);
                                        }
                                    }
                                });

                                $body.append($div);
                            }
                        };
                        if (window.top == window.self) {
                            $.yqDialog(_pops);
                        }
                        else {
                            window.top.$.yqDialog(_pops);
                        }
                    }
                };

            case "theme_init":  //初始化页面css
                var __l = localStorage.getItem('easyui_theme');
                if (__l === null) {
                    __l = "default";
                }
                var __link = $('#easyui_themes');
                var __href = '/yqwin/easyui/themes/' + __l + '/easyui.css';
                if (__href != __link.attr('href')) {
                    __link.attr('href', __href);
                }
            case "midWin_set":
                if (window.top == window.self) {
                    $("body").data("midWin", param);
                }
                else {
                    window.top.$("body").data("midWin", param);
                }
                break;
            case "midWin_get":
                if (window.top == window.self) {
                    return $("body").data("midWin");
                }
                else {
                    return window.top.$("body").data("midWin");
                }

            case "editwin":    //在编辑区域添加页面
                var $midWin = $.yqFormMdi_fun("midWin_get");
                if ($midWin === undefined || $midWin === null) {
                    console.log("No MDI window found",param);
                } else {
                    $midWin.yqFormMdi("editwin", param)
                }
                break;

            case "menuwin": //在菜单区域添加页面
                var $midWin = $.yqFormMdi_fun("midWin_get");
                if ($midWin === undefined || $midWin === null) {
                    console.log("No MDI window found",param);
                } else {
                    $midWin.yqFormMdi("menuwin", param)
                }
                break;

            case "editwin_get":
                var $midWin = $.yqFormMdi_fun("midWin_get");
                if ($midWin === undefined || $midWin === null) {
                    console.log("No MDI window found",param);
                    return null;
                } else {
                    return $midWin.yqFormMdi("editwin_get", param)
                }
            case "menuwin_get":
                var $midWin = $.yqFormMdi_fun("midWin_get");
                if ($midWin === undefined || $midWin === null) {
                    console.log("No MDI window found",param);
                    return null;
                } else {
                    return $midWin.yqFormMdi("menuwin_get", param)
                }
            case "num":  //获取iframe编号
                var p_iframenum = $.urlRequest("iframenum");
                return p_iframenum == "" ? null : p_iframenum;
            case "location":
                var a_para = "";
                var appno = $.urlRequest("appno");
                var menuno = $.urlRequest("menuno");
                var _frame = $.urlRequest("_frame");
                var iframenum = $.urlRequest("iframenum");
                if (appno != "") {
                    a_para += (a_para == "" ? "" : "&") + "appno=" + appno;
                }
                if (menuno != "") {
                    a_para += (a_para == "" ? "" : "&") + "menuno=" + menuno;
                }
                if (_frame != "") {
                    a_para += (a_para == "" ? "" : "&") + "_frame=" + _frame;
                }
                if (iframenum != "") {
                    a_para += (a_para == "" ? "" : "&") + "iframenum=" + iframenum;
                }
                param += (param.indexOf("?") > 0 ? "&" : "?") + a_para;

                location = param;
                break;

            case value2:

                break;
            default:

        }
    }

});

(function ($) {
    $.fn.yqFormMdi = function (options, param) {
        if (typeof options == 'string') {
            return $.fn.yqFormMdi.methods[options](this, param);
        }

        return this.each(function () {
            $this = $(this);
            var o = $.extend({}, $.fn.yqFormMdi.defaults, options);

            var $uniqueID = $this.attr("ID");
            if ($uniqueID === undefined) {
                var id = 'yyxxxxxxxx'.replace(/[xy]/g, function (c) {
                    var r = Math.random() * 16 | 0,
                        v = c == 'x' ? r : (r & 0x3 | 0x8);
                    return v.toString(16);
                });

                $this.attr("ID", id);
            }

            o.admin = false;  //管理员权限
            //变量信息
            $this.data("formmdi_opt", o);

            $this.css({ "margin": "0px", "overflow": "hidden" });

            initMenus($this);
        });
    };

    $.fn.yqFormMdi.defaults = {
        ajaxUrl: "/_db.html", //ajax地址

        pwin: $(window),       //父项页面容器,处理缩放用
        loadmenu: false,       //加载系统菜单
        appno: 1,              //菜单no

        topmenu_l: [],
        topmenu_r: [],

        defleft: null,  //默认左侧页面
        defedit: null,  //默认编辑页面
        defeditText: "首页",

        beforeBindingTitle: function (callback) {
            callback();
        }, //标题绑定前
        afterBindingTitle: function () { }, //标题绑定后
    };

    $.fn.yqFormMdi.methods = {
        options: function (jq) {
            return options($(jq[0]));
        },
        editwin: function (jq, res) {        //在编辑区域添加页面
            editwindow($(jq[0]), res);
        },
        menuwin: function (jq, res) {       //在菜单区域添加页面
            menuwindow($(jq[0]), res);
        },
        editwin_get: function (jq, id) {   //取得菜单页面项目 非jquery对象。
            return editwindow_get($(jq[0]), id);
        },
        menuwin_get: function (jq, id) {   //取得菜单页面项目 非jquery对象。
            return menuwindow_get($(jq[0]), id);
        },
        destroy: function (jq) {
            destroy($(jq[0]));
        },
    };

    function options($object) {
        return $object.data("formmdi_opt");
    }

    function form_load($object) {
        var opt = options($object);
        opt.pwin.resize(function () {
            onresize($object);
        });
        onresize($object);

        if (!(opt.defleft === null)) {
            menuwindow($object, opt.defleft);
        }

        opt.afterBindingTitle.call($object);
    }

    function onresize($object) {
        var opt = options($object);

        var h = opt.pwin.height();
        if (typeof opt.frame != "undefined") {
            opt.frame.layout("resize", {
                width: '100%',
                height: h - 34
            });
        }

        if (typeof opt.forms != "undefined") {
            opt.forms.tabs("resize", {
                width: '100%',
                height: h - 34
            });
        }
        if (typeof opt.lefttabs != "undefined") {
            opt.lefttabs.tabs("resize", {
                width: '100%',
                height: h - 74
            });
        }
    }

    function destroy($object) {
        var opt = options($object);
        $object.find(".yqmdi").remove();
        delete opt.frame;
        delete opt.forms;
        delete opt.lefttabs;
    }

    function initMenus($object) {
        var opt = options($object);
        var $uniqueID = $object.attr("id");

        // $.yqAddCSS(`
        // body {
        //     margin: 0px;
        // }

        // table {
        //     border-spacing: 0px;
        // }

        // .menutop{
        //     padding:1px 1px 1px 2px;
        //     background-color: #f8fbff;
        //     z-index:99;
        // }

        // .yqmdi .tabs {
        //     border-style: solid;
        //     background-color: #f8fbff;
        // }

        // .yqmdi>.layout-panel-west>.panel-header{
        //     border-top-width: 1px;
        // }

        // .yqmdi .tabs-header {
        //     padding-top: 0;
        // }

        // .yqmdi>.layout-panel-center>.panel-header {
        //     border-width: 0;
        // }
        // `, "form.mdi");

        if (opt.loadmenu) {
            $.yqDbMenus({
                ajaxUrl: opt.ajaxUrl,
                appno: opt.appno
            }, function (res) {
                //console.log("yqDbMenus",res);
                if (res.error == 0) {
                    if (res.rows.length == 0) {
                        res.rows = [
                            {
                                "sid": "sid-9",
                                "pid": null,
                                "menu_type": 0,
                                "no": 900,
                                "name": "测试文件夹",
                                "describe": null,
                                "func": null,
                                "icon": null,
                                "icon_on": null,
                                "open_more": false,
                                "remark": null,
                                "queue": 2
                            },

                            {
                                "sid": "sid-901",
                                "pid": "sid-9",
                                "menu_type": 1,
                                "no": 901,
                                "name": "datagrid",
                                "describe": null,
                                "func": "center://adp/test/datagrid.html",
                                "icon": null,
                                "icon_on": null,
                                "open_more": true,
                                "remark": null,
                                "queue": 2
                            },
                        ];
                    }

                    opt.admin = res.admin;
                    opt.topmenu_l = dbToMenusData($object, res.rows, null);
                    opt.beforeBindingTitle.call($object, function () {
                        initLayout($object);
                    });
                }
            });
        }
        else {
            opt.beforeBindingTitle.call($object, function () {
                initLayout($object);
            });
        }
    }

    function dbToMenusData($object, rows, pid) {
        var opt = options($object);

        var menus = [];
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            var _pid = row["pid"];
            if (_pid === undefined || _pid == "") {
                _pid = null;
            }
            if (pid == _pid) {
                var menu = { id: "no" + row["sid"].replace("-", ""), "text": row["name"] };
                var icon = row["icon"];
                if (icon && (typeof icon == "object" || typeof icon == "string")) {
                    // 安全解析JSON字符串
                    try {
                        if(typeof icon == "string"){
                            icon = JSON.parse(icon);
                        }
                        
                        if (icon && icon.sid) {
                            // 生成图标CSS样式
                            var filevalue = $.getFileLink(icon);
                            var cssName = "icon" + icon.sid.replace(/-/g, "");
                            var cssText = '.' + cssName + '{background:url(\'' + filevalue + '\') no-repeat center center;}';
                            $.yqAddCSS(cssText, cssName);
                            menu.iconCls = cssName;
                        }
                    } catch (e) {
                        console.error("解析图标JSON失败:", e, icon);
                    }
                }

                if (row["menu_type"] == 0) {
                    var menus_c = dbToMenusData($object, rows, row["sid"]);
                    if (menus_c.length > 0) {
                        menu.subs = menus_c;
                        menus.push(menu);
                    }
                }
                else if (row["menu_type"] == 1) {
                    var func = row["func"];
                    if (func === undefined || func === null) {
                        func = "";
                    }
                    if (func.length > 0) {
                        func = func + (func.indexOf("?") == -1 ? "?" : "&") + "appno=" + opt.appno + "&menuno=" + row["no"];
                    }
                    menu.openmore = (row["open_more"] === undefined ? false : row["open_more"]);
                    menu.options = {
                        mdi_target: $object,
                        id: "menu" + row["sid"].replace("-", ""),
                        title: row["name"],
                        func: func,
                        openmore: (row["open_more"] === undefined ? false : row["open_more"])
                    };

                    if (typeof menu.iconCls != "undefined") {
                        menu.options.iconCls = menu.iconCls;
                    }

                    menu.onClick = function () {
                        var opts = $(this).data("menu-opt");
                        menuClick(opts);
                    }
                    menus.push(menu);
                }
                else if (row["menu_type"] == 9) {
                    menu = {};
                    menus.push(menu);
                }
            }
        }

        return menus;
    }

    function menuClick(opts) {
        var o = $.extend({
            mdi_target: $("body"),
            id: "id1111",
            title: '菜单1',
            func: "",
            openmore: false,
        }, opts);

        var position = "center";
        var url = "";
        if (o.func.indexOf("left://") == 0) {
            position = "left";
            url = o.func.substring(6);
        }
        else if (o.func.indexOf("center://") == 0) {
            position = "center";
            url = o.func.substring(8);
        }
        else if (o.func.indexOf("right://") == 0) {
            position = "right";
            var url = o.func.substring(7);
        }
        else if (o.func.indexOf("blank://") == 0) {
            position = "blank";
            var url = o.func.substring(7);
        }
        else {
            url = o.func;
        }

        if (url.substring(0, 1) != "/") {
            url = "/" + url;
        }

        var pp = {
            id: o.id,
            title: o.title,
            openmore: o.openmore,
            url: url
        }

        if (typeof o.iconCls != "undefined") {
            pp.iconCls = o.iconCls;
        }

        if (position == "left") {   //左侧菜单
            menuwindow(o.mdi_target, pp);
        } else if (position == "blank") {   //新页面打开
            window.open(pp.url);
        } else {
            editwindow(o.mdi_target, pp);   //居中页面
        }
    }

    function initLayout($object) {
        var opt = options($object);

        opt.topmenu_l_div = $('<div name="_top" class="menutop" style="z-index:99;"></div>');
        opt.topmenu_r_div = $('<div style="position:absolute;right:2px;top:1px;z-index:99"></div>');
        opt.frame = $('<div class="yqmdi"></div>');
        var cd = $object.find("div");
        if (cd.length == 0) {
            $object.prepend(opt.topmenu_l_div);
        }
        else {
            cd.after(opt.topmenu_l_div);
        }
        opt.topmenu_l_div.after(opt.topmenu_r_div);
        opt.topmenu_l_div.after(opt.frame);

        var h = opt.pwin.height();

        opt.frame.layout({
            width: '100%',
            height: h - 41,
            border: false,
            onAdd: function (region) {
                if (region == "center") {
                    opt.forms = $(opt.frame.layout("panel", region).panel("body").find("div")[0]);
                    initEditTabs($object);
                }
            }
        });

        opt.frame.layout("add", {
            region: "center",
            border: false,
            content: '<div id="m_latout"></div>',
        });

        //$("#m_latout").parent().css({"border":"0"});
    }

    function initEditTabs($object) {
        var opt = options($object);
        var h = opt.pwin.height();

        opt.forms.tabs({
            width: '100%',
            height: h - 125,
            plain: true,
            fit: true,
            border: false,
            onAdd: function (title, index) {
                var tabs = opt.forms.tabs("tabs");
                var $last_tab = $(tabs[tabs.length - 1]);
                $last_tab.css("overflow", "hidden");
                /*双击关闭TAB选项卡*/

                var $tabs_inner = opt.forms.find(".tabs-inner");
                $tabs_inner.unbind();
                $tabs_inner.dblclick(function () {
                    var tab = opt.forms.tabs("getSelected");
                    var index = opt.forms.tabs('getTabIndex', tab);
                    if (index > 0) {
                        opt.forms.tabs('close', opt.forms.tabs('getTabIndex', tab));
                    }
                })
            },
            onContextMenu: function (e, title, index) {
                var tab = opt.forms.tabs('getSelected');
                var s_index = opt.forms.tabs('getTabIndex', tab);
                if (s_index != index) {
                    return;
                }

                if (opt.formspop == undefined) {
                    var mms = '<div class="easyui-menu" style="width: 100px;">';
                    mms += '    <div class="tabclose" data-options="iconCls:\'yqwin-btn-icon-sub fa fa-window-close-o\'">关闭</div>';
                    mms += '    <div class="tabcloseall" data-options="iconCls:\'yqwin-btn-icon-sub fa fa-clone\'">全部关闭</div>';
                    mms += '    <div class="tabcloseother" data-options="iconCls:\'yqwin-btn-icon-sub fa fa-columns\'">关闭其它</div>';
                    mms += '    <div class="menu-sep"></div>';
                    mms += '    <div class="tabcloseright" data-options="iconCls:\'yqwin-btn-icon-sub fa fa-caret-square-o-right\'">关闭右侧</div>';
                    mms += '    <div class="tabcloseleft" data-options="iconCls:\'yqwin-btn-icon-sub fa fa-caret-square-o-left\'">关闭左侧</div>';
                    mms += '    <div class="menu-sep"></div>';
                    mms += '    <div class="tabreload" data-options="iconCls:\'yqwin-btn-icon-sub fa fa-refresh\'">刷新页面</div>';

                    if (opt.admin) {
                        mms += '    <div class="tabblank" data-options="iconCls:\'yqwin-btn-icon-sub fa fa-paper-plane\'">新页面打开</div>';
                        mms += '    <div class="tabadmin" data-options="iconCls:\'yqwin-btn-icon-sub fa fa-pencil-square-o\'">页面编辑</div>';
                    }
                    mms += '</div>';

                    var $mms = $(mms);
                    opt.formspop = $mms;
                    $mms.menu({});

                    FormsPopEven($object);
                }

                e.preventDefault();
                opt.formspop.menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });

                FormsPopMenuShow($object, index);
            }
        });

        if (opt.defedit === null) {
            editwindow($object, {
                id: "index",
                title: opt.defeditText,
                openmore: true,
                content: '<button onclick="addmenu();">menu</button><button onclick="addedit();">edir</button>',
                closable: false,
            })
        }
        else {
            editwindow($object, {
                id: "index",
                title: opt.defeditText,
                openmore: true,
                url: opt.defedit,
                closable: false,
            })
        }

        initTopmenu($object);
    }

    //顶部菜单
    function initTopmenu($object) {
        var opt = options($object);

        var $uniqueID = $object.attr("id");
        if (opt.topmenu_l.length > 0) {
            opt.topmenu_l_div.yqTopMenu({
                menus: opt.topmenu_l,
                afterBindingTitle: function () {
                    if (opt.topmenu_r.length > 0) {
                        opt.topmenu_r_div.yqTopMenu({
                            menus: opt.topmenu_r,
                            afterBindingTitle: function () {
                                form_load($object);
                            },
                        });
                    }
                    else {
                        form_load($object);
                    }
                },
            });

            return;
        }

        if (opt.topmenu_r.length > 0) {
            opt.topmenu_r_div.yqTopMenu({
                menus: opt.topmenu_r,
                afterBindingTitle: function () {
                    form_load($object);
                },
            });
        }
        else {
            form_load($object);
        }
    }

    function menuwindow($object, res) {
        var opt = options($object);

        var west_panel = opt.frame.layout("panel", "west");

        if (west_panel.length == 0) {
            opt.frame.layout("add", {
                region: "west",
                width: 300,
                height: "100%",
                split: true,
                hideCollapsedContent: false,
                title: "菜单",
                content: '<div style="bottom:0px;"></div>',
                border: false,
            });

            var h = $object.height();
            //opt.lefttabs = $("#left_tabs");

            opt.lefttabs = $(opt.frame.layout("panel", "west").panel("body").find("div")[0]);

            var opt_tabs = {
                with: "100%",
                height: h - 81,
                tabPosition: "bottom",
                showHeader: false,
                fit: true,
                border: false,
                onAdd: function (title, index) {
                    var tabs = opt.lefttabs.tabs("tabs");
                    var $last_tab = $(tabs[tabs.length - 1]);
                    $last_tab.css({ "overflow": "hidden" });

                    menuwindow_upp($object);
                },
                onClose: function (title, index) {
                    menuwindow_upp($object);
                },

            };

            opt_tabs.onContextMenu = function (e, title, index) {
                var tab = opt.lefttabs.tabs('getSelected');
                var s_index = opt.lefttabs.tabs('getTabIndex', tab);
                if (s_index != index) {
                    return;
                }

                if (opt.leftpop == undefined) {
                    var leftpop_ = `<div style="width:80px;"><div data-options="name:'reload',iconCls:'yqwin-btn-icon-sub fa fa-refresh'">页面刷新</div>`;
                    if (opt.admin) {
                        leftpop_ += `<div data-options="name:'blank',iconCls:'yqwin-btn-icon-sub fa fa-paper-plane'">新页面打开</div>`;
                        leftpop_ += `<div data-options="name:'edit',iconCls:'yqwin-btn-icon-sub fa fa-pencil-square-o'">页面编辑</div>`;
                    }
                    leftpop_ += '</div>';
                    opt.leftpop = $(leftpop_);
                    opt.leftpop.menu({
                        onClick: function (item) {
                            if (item.name == "reload") {
                                var $iframe = opt.lefttabs.tabs('getSelected').panel("body").find("iframe");
                                $iframe[0].contentWindow.location.reload();
                            } else if (item.name == "blank") {
                                window.open(opt.lefttabs.tabs('getSelected').panel("options")._url);
                            } else if (item.name == "edit") {
                                fileget(opt.lefttabs.tabs('getSelected').panel("options")._url);
                            }
                        }
                    });
                }

                e.preventDefault();
                opt.leftpop.menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });
            };

            opt.lefttabs.tabs(opt_tabs);
        }

        var res = $.extend({
            id: "",
            title: "",
            openmore: false,
            content: "",
            url: "",
            closable: true,
        }, res)

        res.title = CutStr(res.title, 20);

        if (!res.openmore && res.id.length > 0) {
            var tabs = opt.lefttabs.tabs('tabs');
            for (var i = 0; i < tabs.length; i++) {
                if ($(tabs[i]).attr("id") == "l_tabs_" + res.id) {
                    opt.lefttabs.tabs('select', i);
                    return;
                }
            }
        }

        var para = {
            title: res.title,
            closable: res.closable,
            selected: true
        };

        if (typeof res.iconCls != "undefined") {
            para.iconCls = res.iconCls;
        }

        if (res.url.length > 0) {
            if (opt.admin) {
                if (res.url.indexOf("?") == -1) {
                    para._url = res.url;
                } else {
                    para._url = res.url.substring(0, res.url.indexOf("?"));
                }
            }
            var keyid = $.getKeyAdd()
            var _url = res.url + (res.url.indexOf("?") == -1 ? "?" : "&") + "_frame=left" + "&iframenum=" + keyid;
            para.content = '<iframe id="iframe_' + keyid + '" style="width:100%;height:100%;" scrolling="auto" frameborder="0" src="' + _url + '"></iframe>';
            para.id2 = keyid;
        }
        else {
            para.content = res.content;
        }

        if (!res.openmore) {
            para.id = "l_tabs_" + res.id;
        }

        opt.lefttabs.tabs('add', para);
    }

    //取得当前id页面对象
    function menuwindow_get($object, id) {
        var opt = options($object);

        var west_panel = opt.frame.layout("panel", "west");
        if (west_panel.length == 0) {
            return null;
        }

        var tabs = opt.lefttabs.tabs('tabs');
        for (var i = 0; i < tabs.length; i++) {
            var tab_opt = opt.lefttabs.tabs('getTab', i).panel("options");
            if (tab_opt.id == "l_tabs_" + id || tab_opt.id2 == id) {
                var cc = opt.lefttabs.tabs('getTab', i).panel("body").children()[0];
                if (cc.tagName.toLowerCase() == "iframe") {
                    return cc.contentWindow;
                }
                else {
                    return cc;
                }
            }
        }

        return null;
    }

    function menuwindow_upp($object) {
        var opt = options($object);

        var tabs = opt.lefttabs.tabs("tabs");
        var west_panel = opt.frame.layout("panel", "west");
        if (tabs.length == 0) {
            opt.frame.layout("remove", "west");
            delete opt.lefttabs;
        }
        else if (tabs.length == 1) {
            opt.lefttabs.tabs("hideHeader");
            west_panel.panel("setTitle", opt.lefttabs.tabs("getTab", 0).panel("options").title + '<a id="left_tabs_reload" title="刷新页面" style="margin-left:10px;margin-top: -5px;"></a>' +
                (opt.admin ? '<a id="left_tabs_edit" title="页面编辑" style="margin-top: -5px;"></a><a id="left_tabs_blank" title="新页面打开" style="margin-top: -5px;"></a>' : "") + '<a id="left_tabs_close" title="关闭" style="margin-top: -5px;"></a>');

            $("#left_tabs_reload").linkbutton({
                iconCls: 'yqwin-btn-icon fa fa-refresh',
                plain: true,
                onClick: function () {
                    var $iframe = opt.lefttabs.tabs('getSelected').panel("body").find("iframe");
                    $iframe[0].contentWindow.location.reload();
                }
            });

            if (opt.admin) {
                $("#left_tabs_edit").linkbutton({
                    iconCls: 'yqwin-btn-icon fa fa-pencil-square-o',
                    plain: true,
                    onClick: function () {
                        fileget(opt.lefttabs.tabs('getSelected').panel("options")._url);
                    }
                });
                $("#left_tabs_blank").linkbutton({
                    iconCls: 'yqwin-btn-icon fa fa-paper-plane',
                    plain: true,
                    onClick: function () {
                        console.log(opt.lefttabs.tabs('getSelected').panel("options")._url);
                        window.open(opt.lefttabs.tabs('getSelected').panel("options")._url);
                    }
                });
            }

            $("#left_tabs_close").linkbutton({
                iconCls: 'yqwin-btn-icon fa fa-window-close-o',
                plain: true,
                onClick: function () {
                    opt.frame.layout("remove", "west");
                }
            });
        }
        else {
            opt.lefttabs.tabs("showHeader");
            west_panel.panel("setTitle", "Menu");
        }
    }

    function editwindow($object, res) {
        var opt = options($object);

        var res = $.extend({
            id: "",
            title: "",
            openmore: false,
            content: "",
            url: "",
            closable: true,
        }, res)

        res.title = CutStr(res.title, 20);

        if (!res.openmore && !(res.id === null) && res.id.length > 0) {
            var tabs = opt.forms.tabs('tabs');
            for (var i = 0; i < tabs.length; i++) {
                if ($(tabs[i]).attr("id") == "m_tabs_" + res.id) {
                    opt.forms.tabs('select', i);
                    return;
                }
            }
        }

        var para = {
            title: res.title,
            closable: res.closable,
            selected: true,
            border: false
        };

        if (res.url.length > 0) {
            //console.log(res);
            if (res.url.indexOf("?") == -1) {
                para._url = res.url;
            } else {
                para._url = res.url.substring(0, res.url.indexOf("?"));
            }

            var keyid = $.getKeyAdd()
            var _url = res.url + (res.url.indexOf("?") == -1 ? "?" : "&") + "_frame=center" + "&iframenum=" + keyid;
            para.content = '<iframe id="iframe_' + keyid + '" style="width:100%;height:100%;" scrolling="auto" frameborder="0" src="' + _url + '"></iframe>';
            para.id2 = keyid;
        }
        else {
            para.content = res.content;
        }

        if (!res.openmore) {
            para.id = "m_tabs_" + res.id;
        }

        if (typeof res.iconCls != "undefined") {
            para.iconCls = res.iconCls;
        }

        opt.forms.tabs('add', para);
    }

    //取得当前id页面对象
    function editwindow_get($object, id) {
        var opt = options($object);

        var tabs = opt.forms.tabs('tabs');
        for (var i = 0; i < tabs.length; i++) {
            var tab_opt = opt.lefttabs.tabs('getTab', i).panel("options");
            if (tab_opt.id == "l_tabs_" + id || tab_opt.id2 == id) {
                var cc = opt.lefttabs.tabs('getTab', i).panel("body").children()[0];
                if (cc.tagName.toLowerCase() == "iframe") {
                    return cc.contentWindow;
                }
                else {
                    return cc;
                }
            }
        }

        return null;
    }

    /*js截取字符串，中英文都能用  
    * @param str：需要截取的字符串 
    * @param len: 需要截取的长度 
    */
    function CutStr(str, len) {
        if ($.yqGetStrLen(str) <= 20) {
            return str;
        }

        var str_length = 0;
        var str_len = 0;
        str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            a = str.charAt(i);
            str_length++;
            if (encodeURIComponent(a).length > 4) {
                //中文字符的长度经编码之后大于4  
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串；  
        if (str_length < len) {
            return str;
        }
    }

    //显示时
    function FormsPopMenuShow($object, index) {
        var opt = options($object);

        opt.pageSelectIndex = index;
        if (index == 0) {
            opt.formspop.find('.tabclose').attr("disabled", "disabled").css({ "cursor": "default", "opacity": "0.4" });
        }
        else {
            opt.formspop.find('.tabclose').removeAttr("disabled").css({ "cursor": "pointer", "opacity": "1" });
        }

        var tabslenght = opt.forms.tabs("tabs").length;

        //全部关闭
        if (tabslenght == 1) {
            opt.formspop.find('.tabcloseall').attr("disabled", "disabled").css({ "cursor": "default", "opacity": "0.4" });
            opt.formspop.find('.tabcloseother').attr("disabled", "disabled").css({ "cursor": "default", "opacity": "0.4" });
        }
        else {
            opt.formspop.find('.tabcloseall').removeAttr("disabled").css({ "cursor": "pointer", "opacity": "1" });
            opt.formspop.find('.tabcloseother').removeAttr("disabled").css({ "cursor": "pointer", "opacity": "1" });
        }

        if (index != 0 && tabslenght == 2) {
            opt.formspop.find('.tabcloseother').attr("disabled", "disabled").css({ "cursor": "default", "opacity": "0.4" });
        }

        if ((parseInt(index) + 1) == tabslenght) {
            opt.formspop.find('.tabcloseright').attr("disabled", "disabled").css({ "cursor": "default", "opacity": "0.4" });
        }
        else {
            opt.formspop.find('.tabcloseright').removeAttr("disabled").css({ "cursor": "pointer", "opacity": "1" });
        }

        if (index > 1) {
            opt.formspop.find('.tabcloseleft').removeAttr("disabled").css({ "cursor": "pointer", "opacity": "1" });
        }
        else {
            opt.formspop.find('.tabcloseleft').attr("disabled", "disabled").css({ "cursor": "default", "opacity": "0.4" });
        }
    }

    //绑定右键菜单事件
    function FormsPopEven($object) {
        var opt = options($object);

        //关闭当前
        opt.formspop.find('.tabclose').click(function () {
            opt.forms.tabs('close', opt.pageSelectIndex);
            opt.pageSelectIndex = -1;
            return true;
        })
        //全部关闭
        opt.formspop.find('.tabcloseall').click(function () {
            var tabslenght = opt.forms.tabs("tabs").length;
            for (var i = (tabslenght - 1); i > 0; i--) {
                opt.forms.tabs('close', i);
            }
            opt.pageSelectIndex = -1;
            return true;
        });
        //关闭除当前之外的TAB
        opt.formspop.find('.tabcloseother').click(function () {
            var tabslenght = opt.forms.tabs("tabs").length;
            for (var i = (tabslenght - 1); i > 0; i--) {
                if (opt.pageSelectIndex != i) {
                    opt.forms.tabs('close', i);
                }
            }
            tabslenght = opt.forms.tabs("tabs").length;
            opt.pageSelectIndex = -1;

            return true;
        });
        //关闭当前右侧的TAB
        opt.formspop.find('.tabcloseright').click(function () {
            var tabslenght = opt.forms.tabs("tabs").length;
            for (var i = (tabslenght - 1); i > opt.pageSelectIndex; i--) {
                opt.forms.tabs('close', i);
            }
            opt.pageSelectIndex = -1;
            return true;
        });
        //关闭当前左侧的TAB
        opt.formspop.find('.tabcloseleft').click(function () {
            for (var i = (opt.pageSelectIndex - 1); i > 0; i--) {
                opt.forms.tabs('close', i);
            }
            opt.pageSelectIndex = -1;
            return true;
        });

        //刷新页面
        opt.formspop.find('.tabreload').click(function () {
            var tab = opt.forms.tabs('getSelected');
            //console.log(tab.panel("body").html());
            var $iframe = tab.panel("body").find("iframe");
            $iframe[0].contentWindow.location.reload();
            return true;
        });

        //新页面打开编辑
        opt.formspop.find('.tabblank').click(function () {
            var tab = opt.forms.tabs('getSelected');
            var iframe = tab.panel("body").find("iframe")[0];
            if (iframe && iframe.contentWindow) {
                var iframeUrl = iframe.contentWindow.location.href;
                iframeUrl = $.urlRemoveParams(iframeUrl, ["_frame", "iframenum"])
                window.open(iframeUrl);
            }
            return true;
        });

        //编辑页面
        opt.formspop.find('.tabadmin').click(function () {
            var tab = opt.forms.tabs('getSelected');
            var tab_opt = tab.panel("options");
            fileget(tab_opt._url);
            return true;
        });
    }

    //--文件操作 begin-----------------------------
    function fileget(fileid) {
        var formData = new FormData();
        formData.append("action", "fileinfo");
        formData.append("file", fileid);
        $.ajax({
            type: 'POST',
            url: "_resource.html",
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (res) {
                if (res.error != 0) {
                    $.yqMessager("error", res.info + "[" + res.error + "]");
                    return;
                }

                var w_ = $(window).width();
                var w__ = w_ < -900 ? w_ : 900
                var show_pops = {
                    mdiinfo: $.yqGetWindParams(),
                    width: w__,
                    height: $(window).height(),
                    horizontalAlign: "right",
                    goDocEnd: false,
                    data: res.data,
                    isEdit: true
                };

                if (window.top == window.self) {
                    $.yqFilePopEdit(show_pops);
                }
                else {
                    window.top.$.yqFilePopEdit(show_pops);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
            }
        });
    }
    //--文件操作 end-------------------------------
})(jQuery);